package app.myproject.dao;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;

import app.myproject.util.PMF;

public abstract class DAOSupport {
	
	private boolean isLocal = false;
	protected PersistenceManager pm;

	public PersistenceManagerFactory getPersistenceManagerFactory() {
		return PMF.get();
	}
	
	public PersistenceManager getPersistanceManager() {
		if (pm == null) {
			pm = getPersistenceManagerFactory().getPersistenceManager();
		}
		//pm.setDetachAllOnCommit(true);
		//pm.setCopyOnAttach(true);
		return pm;
	}
	
	protected boolean isClosed() {
		if (pm != null) {
			return pm.isClosed();
		}
		return true;
	}
	
	protected PersistenceManager open() {
		if (pm == null || pm.isClosed()) {
			System.out.println("open");
			isLocal = true;			
			pm = getPersistenceManagerFactory().getPersistenceManager();
		}
		return pm;
	}
	
	protected Transaction begin() {
		return begin(getPersistanceManager());
	}
	
	protected void commit() {
		if (isLocal) commit(getPersistanceManager());
	}
	
	protected void rollback() {
		rollback(getPersistanceManager());
	}
	
	protected void close() {
		if (isLocal) releasePersistenceManager(getPersistanceManager());
	}
	
	public static void releasePersistenceManager(PersistenceManager pm) {
		try {
			if (pm != null && !pm.isClosed() && !isActive(pm)) {
				System.out.println("close");
				pm.close();
			}
		} 
		catch(Exception e) { e.printStackTrace(); };
	}

	private static Transaction trans(PersistenceManager pm) {
		return pm != null?pm.currentTransaction():null;
	}
	
	public static boolean isActive(PersistenceManager pm) {
		return isActive(trans(pm));
	}
	
	public static boolean isActive(Transaction tx) {
		return tx != null && tx.isActive();
	}
	
	public static Transaction begin(PersistenceManager pm) {
		return begin(trans(pm));
	}
	
	public static Transaction begin(Transaction tx) {
		if (tx != null && !tx.isActive()) {
			System.out.println("begin");
			tx.begin();
		}
		return tx;
	}

	public static void commit(PersistenceManager pm) {
		commit(trans(pm));
	}
	
	public static void commit(Transaction tx) {
		if (tx != null && tx.isActive()) {
			System.out.println("commit");
			tx.commit();
		}
	}

	public static void rollback(PersistenceManager pm) {
		rollback(trans(pm));
	}
	
	public static void rollback(Transaction tx) {
		if (tx != null && tx.isActive()) {
			System.out.println("rollback");
			tx.rollback();
		}
	}
	
}
